package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"video/models"
)

type VideoController struct {
	beego.Controller
}

func (c *VideoController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	file, header, err := c.GetFile("img")
	defer file.Close()
	if err != nil {
		fmt.Println("获取文件失败")
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	v_id, _ := c.GetInt("v_id")
	title := c.GetString("title")
	profile := c.GetString("profile")
	times := c.GetString("times")
	user := c.GetString("user")

	var video = models.Video{
		VId:     v_id,
		Title:   title,
		Profile: profile,
		Img:     "http://127.0.0.1:8080/" + path,
		Times:   times,
		User:    user,
	}
	err = models.DB.Create(&video).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *VideoController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	title := c.GetString("title")
	where := map[string]string{}
	if title != "" {
		where["title"] = title
	}

	var videos []models.Video
	err := models.DB.Where(where).Find(&videos).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "查询展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "查询展示成功",
		Data: videos,
	}
	c.ServeJSON()
}
